package base.thread_JUC2.chapter01.demo002;

import base.thread_JUC2.chapter01.demo001.Calculator;

import java.io.FileWriter;
import java.io.PrintWriter;

public class TestCase {
    public static void main(String[] args) {

        // 输出线程最大，最小和默认优先级别
        System.out.printf("Minimum Priority: %s\n",Thread.MIN_PRIORITY);
        System.out.printf("Normal Priority: %s\n",Thread.NORM_PRIORITY);
        System.out.printf("Maximun Priority: %s\n",Thread.MAX_PRIORITY);

        Thread threads[] = new Thread[10];
        Thread.State status[] = new Thread.State[10];

        // 给线程组放入10个线程(并设置了线程优先级和名称)
        for (int i=0; i<10; i++){
            threads[i] = new Thread(new Calculator(i));
            if ((i%2) == 0){
                threads[i].setPriority(Thread.MAX_PRIORITY);
            } else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("线程 "+i);
        }


        // 写入文件log.txt
        try (FileWriter file = new FileWriter(".\\data\\log.txt");
             PrintWriter pw = new PrintWriter(file);){

            // 线程状态写入文件log.txt
            for (int i=0; i<10; i++){
                pw.println("Main : Status of Thread "+i+" : "+threads[i].getState());
                status[i]=threads[i].getState();
            }

            // 启动10个线程
            for (int i=0; i<10; i++){
                threads[i].start();
            }

            boolean finish = false;
            while (!finish) {
//                Thread.sleep(2000);//该程序并不能完整反应线程所有状态，假定这里main方法执行到此，所有10个线程都执行完毕了，10个线程状态都为 TERMINATED呢
                // 检查10个线程是否状态变化，有变化则记录日志中，并更新线程状态数组status为对应线程最新状态
                for (int i=0; i<10; i++){
                    if (threads[i].getState()!=status[i]) {
                        writeThreadInfo(pw, threads[i],status[i]);
                        status[i]=threads[i].getState();
                    }
                }

                finish=true;
                for (int i=0; i<10; i++){
                    finish=finish &&(threads[i].getState()== Thread.State.TERMINATED);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State state) {
        pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
        pw.printf("Main : Priority: %d\n",thread.getPriority());
        pw.printf("Main : Old State: %s\n",state);
        pw.printf("Main : New State: %s\n",thread.getState());
        pw.printf("Main : ************************************\n");
    }
}
